<template>
	<view class="content">
		<g-watermark />
		<view class="content_info">
			<view class="content_info_item">
				发件人：{{ model.sender }}
			</view>
			<view class="content_info_item"> 收件人：{{ model.receiver }} </view>
			<view class="content_info_item"> 时间：{{ model.sendTime }} </view>
			<view class="content_info_item"> 主题：{{ model.subject }} </view>
			<view class="content_info_item" v-if="model.cc && model.cc.length > 0">
				抄送：{{ model.cc }}
			</view>
		</view>
		<view class="content_con">
			<view>
				<rich-text :nodes="model.content" v-if="model.content"></rich-text>
			</view>
			<view style="
          margin-top: 20rpx;
          display: flex;
          flex-direction: column;
          gap: 14rpx;
        " v-if="model.attachments && model.attachments.length">
				<view v-for="(item, index) in model.attachments" :key="index" style="margin-top: 20rpx">
					<a @click="handleDownload(item)">{{ item.name }}</a>
					<a v-if="item.previewUrl" @click="handlePreview(item)" style="margin-left: 5px">预览</a>
				</view>
			</view>
		</view>
		<!-- <view class="content_reply" v-if="type != 'garbageBinbox'">
			<view class="">
				<LEditor v-model="content" ref="lEditorRef" placeholder="快速回复" height="400rpx" />
			</view>
			<view style="margin: 20rpx 0">
				<FileUpload ref="fileUploadRef" style="min-height: 80rpx" :msgId="model.id" />
			</view>
			<view style="margin-top: 40rpx">
				<u-button type="primary" @click="handleSubmit">回 复</u-button>
			</view>
		</view> -->
		<view class="body_bottom">
			<view @click="handleRefresh"> 刷新 </view>
			<view @click="handleReply"> 回复 </view>
			<view @click="handleDelete" style="color: red"> 删除 </view>
			<view @click="handleTransmit"> 转发 </view>
		</view>
		<xe-upload ref="XeUpload" :options="{}" @callback="handleUploadCallback"></xe-upload>
	</view>
</template>

<script>
	import {
		postFormAction
	} from "@/utils/request.js";
	import {
		Api
	} from "@/utils/Api";
	import XeUpload from "../../component/xe-upload/components/xe-upload/xe-upload.vue";
	import LEditor from "../../component/l-editor/l-editor.vue";
	import FileUpload from "../../component/file-upload/file-upload.vue";
	import {replaceHtml} from '../common/tools.js'
	import {
		mapState
	} from "vuex";
	export default {
		components: {
			XeUpload,
			LEditor,
			FileUpload,
		},
		data() {
			return {
				url: {
					show: "/email/showMail",
					sendReceipt: "/message_oa/sendReceipt", //回执
					delToDustbin: "/email/delMail",
					// del: "/message_oa/del",
					reply: "/email/reply",
				},
				model: {},
				content: "",
				isDraft: false,
				isDoRefresh: false,
				type: "",
			};
		},
		computed: {
			...mapState(["emailInfo"]),
		},
		onLoad(options) {
			this.mainId = options.mainId;
			this.isDraft = options.isDraft ? true : false;
			this.type = options.type;
			this.fetch();
		},
		//新增完之后刷页面
		onShow(e) {
			const that = this;
			let pages = getCurrentPages();
			//刷新页面
			let currPage = pages[pages.length - 1];
			if (currPage.isDoRefresh == true) {
				currPage.isDoRefresh = false;
				that.fetch();
			}
		},
		methods: {
			async fetch() {
				try {
					if (!this.mainId || !this.emailInfo.id) return;
					uni.showLoading({
						title: "加载中",
						mask: true,
					});
					const res = await postFormAction(this.url.show, {
						id: this.mainId,
						emailId: this.emailInfo.id
					});
					this.model = res.data;
					if(this.model.content){
						// <、>、&
						// &lt;、&gt;、&amp;
						try{
						this.model.content = replaceHtml(this.model.content)
						// this.model.content = this.model.content.replaceAll('&nbsp;',' ')
						}catch(e){
							console.error("HTMLParser",e)
						}
						// this.model.content = `<p>${this.model.content}</p>`
					}
					//根据条件判断回执
					if (res.data.receiptState == 1) {
						handleReceiptState();
					}
					if (res.code != 200) {
						uni.showToast({
							title: res.msg,
							icon: "none",
						});
					}
				} catch (e) {
					uni.hideLoading();
				} finally {
					uni.hideLoading();
				}
			},
			//回执
			handleReceiptState() {
				const that = this;
				uni.showModal({
					title: "提示",
					content: "消息发送者需要回执，现在就发送回执么？",
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: "操作中",
									mask: true,
								});
								const res = await postFormAction(this.url.sendReceipt, {
									id: that.mainId,
								});
								uni.showToast({
									title: res.msg,
									icon: "none",
								});
							} catch (error) {
								console.log(error);
								uni.hideLoading();
							} finally {
								uni.hideLoading();
							}
						}
					},
				});
			},
			handleReturn() {
				var pages = getCurrentPages();
				// var currPage = pages[pages.length - 1]; //当前页面
				var prevPage = pages[pages.length - 2]; //上一个页面
				prevPage.isDoRefresh = true;
				uni.navigateBack();
			},
			handleClear() {
				this.content = "";
				this.$refs.fileUploadRef.fileList = [];
			},
			//刷新
			handleRefresh() {
				this.fetch();
				// this.handleClear();
			},
			//回复
			handleReply() {
				uni.navigateTo({
					url: `/cmn/externalEmail/writebox/index?type=reply&mainId=${this.model.id}`,
				});
			},
			//删除
			async handleDelete() {
				const that = this;
				uni.showModal({
					title: "提示",
					content: "您确定删除么？",
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: "删除中",
									mask: true,
								});
								await postFormAction(that.url.delToDustbin, {
									ids: that.mainId,
									emailId: that.emailInfo.id
								});
								that.handleReturn();
							} catch (e) {
								uni.hideLoading();
							} finally {
								uni.hideLoading();
							}
						}
					},
				});
			},
			//转发
			handleTransmit() {
				uni.navigateTo({
					url: `/cmn/externalEmail/writebox/index?type=transmit&mainId=${this.model.id}`,
				});
			},
			handlePreview(item) {
				uni.navigateTo({
					url: `/application/preview?record=${JSON.stringify({
          url: item.previewUrl,
          name: item.name,
        })}`,
				});
			},
			//下载
			handleDownload(record) {
				if (this.model.isMobileForbidDownload) {
					uni.showToast({
						title: "手机端禁止下载文件",
						icon: "none",
					});
					return;
				}

				const path = record.visualPath + record.diskName;
				const fileName = record.name;
				//这里填写接口地址
				const url = path ?
					Api.baseUrl + (path && path.startsWith("/") ? path : `/${path}`) :
					"";
				// #ifdef H5
				var doma = document.createElement("a");
				doma.download = ""; // 设置下载的文件名，默认是'下载'
				doma.target = "_blank";
				doma.href = url; //临时路径再保存到本地
				document.body.appendChild(doma);
				doma.click();
				doma.remove(); // 下载之后把创建的元素删除
				// #endif
				console.log("开始下载");
				// #ifdef APP || MP-WEIXIN || H5
				uni.downloadFile({
					//调用官方提供的uni.downloadFile
					url: url, //将刚刚提前准备好的url传过来
					header: {
						//如果需要填写请求头信息则在此处填写
					},
					success: function(res) {
						if (res.statusCode === 200) {
							console.log("下载成功：", res.tempFilePath);

							//下载成功，并把下载好的文件保存在临时区域中
							uni.saveFile({
								//使用该功能，以将临时文件保存在手机中可长久存储的区域
								tempFilePath: res.tempFilePath,
								success: (saveResult) => {
									// 在保存文件成功后，使用 uni.openDocument 方法打开文件
									console.log("文件保存成功:", saveResult);
									uni.openDocument({
										filePath: saveResult.savedFilePath,
										// fileType: fileType, //这里把预先限定好的文件类型传来
										success: function() {
											console.log("文件打开成功!");
											//至此，手机会从app中跳转到文件预览界面
											//之后可从预览界面返回app中
										},
										fail: function(err) {
											console.log("打开失败", err);
										},
									});
								},
								fail: function(err) {
									console.log("保存文件失败", err);
								},
							});
						}
					},
					fail: function(err) {
						console.log("下载失败：", err);
					},
				});
				// #endif
			},
			//确定
			// async handleSubmit() {
			// 	console.log("uUpload", this.$refs.fileUploadRef.fileList);
			// 	try {
			// 		console.log("this.model", this.model);
			// 		this.content = this.$refs.lEditorRef.content;
			// 		console.log("content", this.content);
			// 		if (!this.content) {
			// 			uni.showToast({
			// 				title: "请输入内容",
			// 				icon: "none",
			// 			});
			// 			return;
			// 		}
			// 		const params = {
			// 			title: this.model.title,
			// 			id: this.model.id,
			// 			receiver: this.model.sender,
			// 			isDraft: this.isDraft,
			// 			userRealName: this.model.senderRealName,
			// 			content: this.content,
			// 		};
			// 		console.log("params", params);

			// 		const fileList = this.$refs.fileUploadRef.fileList;
			// 		// const files = []
			// 		if (fileList && fileList.length) {
			// 			params.attachments = fileList.map((item) => item.id).join(",");
			// 			// fileList.forEach((item, index) => {
			// 			// 	files.push({
			// 			// 		[`att${index + 1}`]: item,
			// 			// 		name: 'file',
			// 			// 		uri: item.tempFilePath
			// 			// 	})
			// 			// });
			// 		}
			// 		uni.showLoading({
			// 			title: "加载中",
			// 			mask: true,
			// 		});
			// 		await postFormAction(this.url.reply, params);
			// 		this.handleReturn();
			// 	} catch (error) {
			// 		uni.hideLoading();
			// 	} finally {
			// 		uni.hideLoading();
			// 	}
			// },
			bytesToMB(a, b = 2) {
				if (0 == a || !a) return "0 B";
				const c = 1024,
					d = b || 2,
					e = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
					f = Math.floor(Math.log(a) / Math.log(c));
				return parseFloat((a / Math.pow(c, f)).toFixed(d)) + " " + e[f];
			},
		},
	};
</script>

<style lang="less" scoped>
	.content {
		padding-bottom: 100rpx;

		&_info {
			background-color: #efefef;
			border-bottom: 1px solid #acdcdc;
			margin: 20rpx;
			padding: 20rpx;
			display: flex;
			flex-direction: column;
			gap: 20rpx;
		}

		&_con {
			margin: 0 20rpx 20rpx;
			min-height: 200rpx;
		}

		&_reply {
			margin: 40rpx 20rpx 800rpx;
		}
	}

	.body_bottom {
		position: fixed;
		bottom: 0;
		z-index: 10;
		height: 100rpx;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-around;
		gap: 20rpx;
		background: #ffffff;
		box-shadow: 0rpx -2rpx 16rpx 0rpx rgba(0, 0, 0, 0.1);
	}
</style>